package com.ccp.dev.extend.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.form.consts.FormConstants;
import com.ccp.dev.form.model.DialogField;
import com.ccp.dev.form.model.FormDialog;
import com.ccp.dev.form.service.FormDialogService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 扩展的自定义对话框控制器类
 *
 * @author 创新中心-王明亮
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + "/extend/formDialog")
@Action(ownermodel = SysAuditModelType.FORM_MANAGEMENT)
public class ExtendFormDialogController extends SysBaseController {

    @Resource
    private FormDialogService formDialogService;

    /**
     * 数据列表页面跳转
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/list")
    @Action(description = "自定义对话框列表页面跳转", exectype = "页面跳转日志")
    public String formDialogViewList() {
        return getAutoView();
    }

    /**
     * 设置列页面跳转
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/setCol")
    @Action(description = "自定义对话框设置列页面跳转", exectype = "页面跳转日志")
    public String formDialogViewSetCol(HttpServletRequest request, ModelMap modelMap) {
        String dsName = RequestUtil.getString(request, "dsName");
        String formDialogId = RequestUtil.getString(request, "formDialogId");
        String showStyle = RequestUtil.getString(request, "showStyle");
        int isTable = RequestUtil.getInt(request, "isTable");
        String objectName = RequestUtil.getString(request, "objectName");
        modelMap.put("showStyle", showStyle);
        modelMap.put("dsName", dsName);
        modelMap.put("isTable", isTable);
        modelMap.put("objectName", objectName);
        modelMap.put("formDialogId", formDialogId);
        return getAutoView();
    }

    /**
     * 新增页面跳转
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/add")
    @Action(description = "自定义对话框新增页面跳转", exectype = "页面跳转日志")
    public String formDialogViewAdd(HttpServletRequest request, ModelMap modelMap) {
        String formDialogId = RequestUtil.getString(request, "formDialogId");
        modelMap.put("formDialogId", formDialogId);
        if (StringUtil.isNotEmpty(formDialogId)) {
            FormDialog formDialog = formDialogService.getOneById(formDialogId);
            modelMap.put("formDialog", formDialog);
        }
        return "form/formDialog/addEdit";
    }

    /**
     * 展示json数据页面跳转
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/showJson")
    @Action(description = "自定义对话框展示json数据页面跳转", exectype = "页面跳转日志")
    public String showJson(HttpServletRequest request, ModelMap modelMap) {
        String parentName = RequestUtil.getString(request, "parentName");
        modelMap.put("parentName", parentName);
        return getAutoView();
    }

    /**
     * 开发帮助页面跳转
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/assist")
    @Action(description = "自定义对话框开发帮助页面跳转", exectype = "页面跳转日志")
    public String formDialogViewAssist() {
        return getAutoView();
    }

    /**
     * 对话框页面跳转
     *
     * @param request  请求
     * @param modelMap modelMap
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/show")
    @Action(description = "对话框预览页面跳转", exectype = "页面跳转日志")
    public String showFrame(HttpServletRequest request, ModelMap modelMap) {
        Map<String, Object> paramsMap = RequestUtil.getQueryMap(request);
        String nextUrl = RequestUtil.getUrl(request);
        String cs = "";
        java.util.Set<String> set = paramsMap.keySet();
        java.util.Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Object str = iterator.next();
            Object s = paramsMap.get(str);
            cs += "&" + str + "=" + s;
        }
        String alias = RequestUtil.getString(request, "alias");
        FormDialog bpmFormDialog = formDialogService.getByAlias(alias);
        modelMap.put("bpmFormDialog", bpmFormDialog);

        //是否需要先跳转到动态传入参数页面
        boolean dynamicPage = RequestUtil.getBoolean(request, "dynamicPage");
        boolean isOpenJsonData = RequestUtil.getBoolean(request, "isOpenJsonData");
        boolean isOpenShowDialog = RequestUtil.getBoolean(request, "isOpenShowDialog");
        modelMap.put("isOpenShowDialog", isOpenShowDialog);
        if (dynamicPage) {
            List<DialogField> conditionList = bpmFormDialog.getConditionList();
            for (DialogField dialogField : conditionList) {
                if (dialogField.getDefaultType() == DialogField.DEFAULT_TYPE_DYNAMIC_AFFERENT) {
                    return "form/formDialog/dynamicAfferent";
                }
            }
        }

        // 需要排序
        if (bpmFormDialog.getStyle() == FormDialog.STYLE_LIST) {
            String sortField = RequestUtil.getString(request, "sortField");
            String orderSeq = RequestUtil.getString(request, "orderSeq", FormDialog.DEFAULT_ORDER_SEQ);
            String newSortField = RequestUtil.getString(request, "newSortField");
            if (StringUtil.isNotEmpty(sortField)) {
                paramsMap.put("sortField", sortField);
                paramsMap.put("orderSeq", orderSeq);
            }
            if (StringUtil.isEmpty(sortField)) {
                DialogField dialogField;
                if (BeanUtils.isNotEmpty(bpmFormDialog.getSortList())) {
                    dialogField = bpmFormDialog.getSortList().get(0);
                    sortField = dialogField.getFieldName();
                    orderSeq = dialogField.getComment();
                } else {
                    dialogField = bpmFormDialog.getDisplayList().get(0);
                    sortField = dialogField.getFieldName();
                }
            }
            if (newSortField.equals(sortField)) {
                if ("ASC".equals(orderSeq)) {
                    orderSeq = "DESC";
                } else {
                    orderSeq = "ASC";
                }
            }
            if (!StringUtil.isEmpty(newSortField)) {
                sortField = newSortField;
            }
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("sortField", StringUtil.isEmpty(newSortField) ? sortField : newSortField);
            parameters.put("newSortField", null);
            parameters.put("orderSeq", orderSeq);
            modelMap.put("sortField", sortField);
            modelMap.put("orderSeq", orderSeq);
            modelMap.put("baseHref", nextUrl);
            modelMap.put("paramsMap", paramsMap);
        } else {
            // 树 对话框
            modelMap.put("urlPara", cs);
        }
        modelMap.put("paramStr", cs);
        modelMap.put("isOpenJsonData", isOpenJsonData);
        modelMap.put("alias", alias);
        String retUrl = getAutoView();
        if (isOpenShowDialog) {
            retUrl = "extend/formDialog/showDialog";
        }
        return retUrl;
    }

    /**
     * 查询对话框列表数据
     * 2019-10-31 传入参数有重复时，会自动生成数组，将自动生成的字符串数组保留最后一个值
     *
     * @param request 请求
     * @return ResultData
     */
    @RequestMapping("/showTableData")
    @ResponseBody
    @Action(description = "查询对话框列表数据", exectype = "查询日志",
            detail = "查询对话框列表数据【${name}】<#if success>成功<#else>失败</#if>")
    public ResultData showTableData(HttpServletRequest request) {
        Map<String, Object> paramsMap = RequestUtil.getQueryMap(request);
        for (String key : paramsMap.keySet()) {
            if (paramsMap.get(key) instanceof String[]) {
                String[] valueStr = (String[]) paramsMap.get(key);
                paramsMap.put(key, valueStr[valueStr.length - 1]);
            }
        }
        String alias = RequestUtil.getString(request, "alias");
        FormDialog bpmFormDialog = formDialogService.getByAlias(alias);
        try {
            bpmFormDialog = formDialogService.getData(bpmFormDialog, paramsMap);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            SysAuditThreadLocalHolder.putParamerter("name", bpmFormDialog.getName());
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return getResultDataSuccess("query.success", bpmFormDialog.getPageBean().getTotalCount(), bpmFormDialog.getList());
    }

    /**
     * 取得自定义对话框分页列表
     *
     * @param request HttpServletRequest
     * @return ResultData
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description = "查询自定义对话框分页列表", exectype = "查询日志",
            detail = "查询自定义对话框分页列表<#if success>成功<#else>失败</#if>")
    public ResultData list(HttpServletRequest request) {
        QueryFilter filter = new QueryFilter(request);
        boolean needPage = RequestUtil.getBoolean(request, "needPage");
        if (needPage) {
            filter = new QueryFilter(request, true);
        }
        try {
            List<FormDialog> formDialogList = formDialogService.queryList(filter);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("query.success", filter.getPageBean().getTotalCount(), formDialogList);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 删除自定义对话框
     *
     * @param request HttpServletRequest
     * @return ResultData
     */
    @RequestMapping("/del")
    @ResponseBody
    @Action(description = "删除自定义对话框", exectype = "删除日志", detail = "删除自定义对话框<#if success>成功<#else>失败</#if>")
    public ResultData del(HttpServletRequest request) {
        try {
            String[] ids = RequestUtil.getStringAryByStr(request, "ids");
            int result = formDialogService.delByIdArray(ids);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("delete.failure");
        }
    }

    /**
     * 添加或更新通用表单对话框
     *
     * @param formDialog 添加或更新的实体
     * @return ResultData
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @ResponseBody
    @Action(description = "添加或更新通用表单对话框", exectype = "添加或更新日志",
            detail = "<#if isAdd==0>添加<#else>更新</#if>" +
                    "通用表对话框【${name}】<#if success>成功<#else>失败</#if>")
    public ResultData save(@RequestBody FormDialog formDialog) {
        if (StringUtil.isEmpty(formDialog.getDisplayfield())) {
            return getResultDataError("formDialog.displayField.warn");
        }
        if (StringUtil.isEmpty(formDialog.getResultfield())) {
            return getResultDataError("formDialog.resultField.warn");
        }
        boolean isExist = formDialogService.isExistAlias(formDialog.getAlias(), formDialog.getId());
        if (isExist) {
            return getResultDataError("formDialog.alias.warn");
        }
        try {
            formDialogService.addOrUpdate(formDialog);
            SysAuditThreadLocalHolder.putParamerter("isAdd", formDialog.getId() == null ? 0 : 1);
            SysAuditThreadLocalHolder.putParamerter("name", formDialog.getName());
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("save.failure");
        }
        return getResultDataSuccess("save.success");
    }

    /**
     * 查看通用表单对话框明细
     *
     * @param request
     * @return
     */
    @RequestMapping("/dialogObj")
    @Action(description = "查看通用表单对话框明细", exectype = "查询日志",
            detail = "查看通用表单对话框明细<#if success>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData dialogObj(HttpServletRequest request) {
        String alias = RequestUtil.getString(request, "alias");
        SysAuditThreadLocalHolder.putParamerter("alias", alias);
        SysAuditThreadLocalHolder.putParamerter("success", false);
        FormDialog bpmFormDialog = formDialogService.getByAlias(alias);
        List<DialogField> conditionList = bpmFormDialog.getConditionList();
        for (DialogField dialogField : conditionList) {
            if (dialogField.getDefaultType() == DialogField.DEFAULT_TYPE_DYNAMIC_AFFERENT) {
                bpmFormDialog.setWidth(450);
                bpmFormDialog.setHeight(400);
            }
        }
        if (bpmFormDialog != null) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        }
        return getResultDataSuccess("query.success", bpmFormDialog);
    }

    /**
     * 取得树形数据
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getTreeData")
    @Action(description = "取得树形数据", exectype = "查询日志",
            detail = "取得树形数据<#if success>成功<#else>失败</#if>")
    @ResponseBody
    public List getTreeData(HttpServletRequest request) throws Exception {
        List list = null;
        String alias = RequestUtil.getString(request, "alias");
        String pvalue = RequestUtil.getString(request, "idKey");
        String pname = RequestUtil.getString(request, "pidKeyName");
        int isRoot = RequestUtil.getInt(request, "isRoot");
        Map<String, Object> params = new HashMap<>(10);
        try {
            if (isRoot == FormConstants.DEFAULT_INT_ONE) {
                params = RequestUtil.getQueryMap(request);
                list = formDialogService.getTreeData(alias, params, true);
            } else {
                params.put("pname", pname);
                params.put("pvalue", pvalue);
                params.put(pname, pvalue);
                list = formDialogService.getTreeData(alias, params, false);
            }
            for (Object obj : list) {
                Map<String, Object> map = (Map<String, Object>) obj;
                Object isParent = map.get("ISPARENT");
                if (isParent != null) {
                    if ("true".equals(isParent.toString())) {
                        map.put("isParent", true);
                    } else {
                        map.put("isParent", false);
                    }
                }
            }
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return list;
    }

    /**
     * 选择自定义对话框
     *
     * @return 自定义对话框列表
     */
    @RequestMapping("/getAllDialogs")
    @Action(description = "查询自定义对话框数据列表", exectype = "查询日志",
            detail = "查询自定义对话框数据列表<#if success>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData getAllDialogs() {
        try {
            List<FormDialog> list = formDialogService.getAllDialogs();
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("query.success", list);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("query.failure");
        }
    }
}
